package com.lupan.practice;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 说明：
 *
 * @author lupan
 * @version 2017/5/18 16:54
 */
public class CardID {

    private String cardNum;

    public String getCardNum() {
        return cardNum;
    }

    public void setCardNum(String cardNum) {
        this.cardNum = cardNum;
    }

    public boolean lengthVerify() {
        return cardNum != null && cardNum.length() == 18;
    }

    public boolean charVerify() {
        char[] array = cardNum.toCharArray();
        for (char c : array) {
            if (!Character.isDigit(c)) {
                System.out.println(String.format("|数字校验错误|错误字符:%s|", c));
                return false;
            }
        }
        return true;
    }

    public boolean checkCodeVerify() {
        char[] array = cardNum.toCharArray();
        int sum = 0;
        for(int i =0;i<18;i++){
            if(i==17){
                array[i] = '0';
            }
            int ai = Integer.parseInt(String.valueOf(array[i]));
            int wi = (int)Math.pow(2,i)%11;
            sum+= ai*wi;
            System.out.println(String.format("i=%s,ai=%s,wi=%s,sum=%s",i+1,ai,wi,sum));
        }

        int checkValue = sum%11;

        Map<Integer,String> checkMap = new HashMap<>();
        checkMap.put(0,"1");
        checkMap.put(1,"0");
        checkMap.put(2,"X");
        checkMap.put(3,"9");
        checkMap.put(4,"8");
        checkMap.put(5,"7");
        checkMap.put(6,"6");
        checkMap.put(7,"5");
        checkMap.put(8,"4");
        checkMap.put(9,"3");
        checkMap.put(10,"2");

        String lastChar = String.valueOf(cardNum.charAt(17));
        if(!checkMap.get(checkValue).equals(lastChar)){
            System.out.println(String.format("|校验码校验错误|错误校验码值:%s，校验码值：%s|",checkMap.get(checkValue),lastChar));
            return false;
        }

        return true;
    }

    public boolean outPut() {

        StringBuffer sb = new StringBuffer(cardNum);
        String year = sb.substring(6,10);
        String month = sb.substring(10,12);
        String day = sb.substring(12,14);
        System.out.println(String.format("生日：%s年%s月%s日",year,Integer.parseInt(month),Integer.parseInt(day)));


        Calendar calendar = Calendar.getInstance();
        int age =  calendar.get(Calendar.YEAR)-Integer.parseInt(year);
        System.out.println(String.format("年龄：%s岁",age));

        int num = Integer.parseInt(sb.substring(14,17));
        String sex;
        if(num%2==1){
            sex = "男";
        }else{
            sex = "女";
        }
        System.out.println(String.format("性别：%s",sex));
        return true;
    }


    public static void main(String[] args) {
        CardID cardID = new CardID();
        cardID.setCardNum("510184199106012418");
        cardID.lengthVerify();
        cardID.charVerify();
        cardID.checkCodeVerify();
        cardID.outPut();
    }

}
